import logging
import time
import random
from datetime import datetime

logger = logging.getLogger(__name__)

class TradeExecutor:
    def __init__(self, db_manager):
        """初始化交易执行器"""
        self.db_manager = db_manager
        self.current_capital = 1000000  # 初始资金
        logger.info("交易执行器初始化完成")
    
    def execute_trade(self, trade_data):
        """执行交易"""
        try:
            logger.info(f"执行交易: {trade_data['master_name']} {trade_data['trade_type']} "
                       f"{trade_data['stock_name']} {trade_data['trade_volume']}股 @ {trade_data['trade_price']}")
            
            # 计算交易金额
            trade_amount = trade_data['trade_price'] * trade_data['trade_volume']
            if trade_data['trade_type'] == '买入':
                trade_amount = -trade_amount  # 买入为负支出
            
            # 更新资金
            self.current_capital += trade_amount
            
            # 保存资金记录
            self.db_manager.save_capital(self.current_capital)
            
            # 模拟执行延迟
            execution_time = random.uniform(0.5, 3.0)
            time.sleep(execution_time)
            
            logger.info(f"交易执行成功，耗时: {execution_time:.2f}秒，当前资金: {self.current_capital:.2f}")
            return True
        except Exception as e:
            logger.error(f"执行交易失败: {str(e)}")
            return False
    
    def execute_follow_trade(self, master_trade):
        """执行跟单交易"""
        try:
            # 复制高手交易
            trade_data = {
                'master_name': master_trade['MasterName'],
                'stock_code': master_trade['StockCode'],
                'stock_name': master_trade['StockName'],
                'trade_type': master_trade['TradeType'],
                'trade_price': master_trade['TradePrice'],
                'trade_volume': master_trade['TradeVolume'],
                'trade_date': datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            }
            
            return self.execute_trade(trade_data)
        except Exception as e:
            logger.error(f"执行跟单失败: {str(e)}")
            return False
    
    def get_current_capital(self):
        """获取当前资金"""
        return self.current_capital